/*
 * This file is part of the eccOS Library.
 * Copyright (C) 2007.
 *
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 */
/*
 * Created on 13/06/2006
 */
package org.openeccos.util;

import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;

import org.hibernate.Criteria;
import org.openeccos.dao.EccosRepository;
import org.openeccos.model.MMailSettings;

import com.sas.framework.expojo.ModelExposer;


/**
 * @author Demián Gutierrez
 */
public class MailBean {

	protected String host;
	protected String port;
	protected String mail;
	protected String user;
	protected String pass;

	// ----------------------------------------

	public MailBean() {
		// Empty
	}

	// ----------------------------------------

	protected Properties getPropertyFromBean(MMailSettings mailSettings) {
		Properties settings = new Properties();

		host = mailSettings.getServerName();
		port = mailSettings.getPortStr();

		mail = mailSettings.getUser();
		user = mailSettings.getUser();
		pass = mailSettings.getPassword();

		// ----------------------------------------
		// Basic settings
		// ----------------------------------------

		settings.put("mail.from", mail);
		settings.put("mail.smtp.host", host);
		settings.put("mail.smtp.port", port);
		settings.put("mail.transport.protocol", "smtp");

		// ----------------------------------------
		// Debug settings
		// ----------------------------------------

		if (mailSettings.isDebug()) {
			settings.put("mail.debug", "true");
		}

		// ----------------------------------------
		// tls settings
		// ----------------------------------------

		if (mailSettings.isStarttls()) {
			settings.put("mail.smtp.socketFactory.port", mailSettings.getPortStr());
			settings.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			settings.put("mail.smtp.socketFactory.fallback", "false");
			settings.put("mail.smtp.starttls.enable", "true");
			settings.put("mail.smtp.ssl", "true");
		}

		// ----------------------------------------
		// Authentication settings
		// ----------------------------------------

		if (mailSettings.isAuth()) {
			String username = mailSettings.getUser();
			settings.put("mail.user", username);
			settings.put("mail.smtp.auth", "true");
		}

		return settings;
	}

	//	 ----------------------------------------

	public void sendMail(List<String> rcptList, String subj, String mess) throws Exception {
		// ----------------------------------------
		// Creates the recipients string
		// ----------------------------------------

		StringBuffer rcptStr = new StringBuffer();

		Iterator<String> itt = rcptList.iterator();

		while (itt.hasNext()) {
			rcptStr.append(itt.next());

			if (itt.hasNext()) {
				rcptList.add(", ");
			}
		}

		sendMail(rcptStr.toString(), subj, mess, false, null);
	}

	//	 ----------------------------------------

	public void sendMail(String rcpt, String subj, String mess, boolean isHtml, List<Attachment> attachments) throws Exception {

		EccosRepository repo = (EccosRepository)ModelExposer.get().getRepository(EccosRepository.NAME);
		MMailSettings mailSettings = (MMailSettings)repo.getFirst(MMailSettings.class);

		if (mailSettings == null) {
			throw new Exception("Mail settings do not exist");
		} else if (!mailSettings.isEnabled()) {
			return;
		}

		// Get properties from mail settings
		Properties settings = getPropertyFromBean(mailSettings);

		// Get mailSession
		javax.mail.Session mailSession;
		if (mailSettings.isAuth()) {
			Authenticator loAuthenticator = new Authenticator() {
				public PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(user, pass);
				}
			};

			mailSession = javax.mail.Session.getInstance(settings, loAuthenticator);
		} else {
			mailSession = javax.mail.Session.getInstance(settings);
		}

		mailSession.setDebug(mailSettings.isDebug());

		Message msg = new MimeMessage(mailSession);
		msg.setFrom(new InternetAddress(mail));
		msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(rcpt, false));
		msg.setSubject(subj);

		if (isHtml) {
			MimeMultipart content = new MimeMultipart();
			MimeBodyPart text = new MimeBodyPart();

			text.setText(mess);
			text.setContent(mess, "text/html");
			content.addBodyPart(text);

			if (attachments != null) {
				for (Attachment attachment : attachments) {
					DataSource source = new ByteArrayDataSource(attachment.getData(), "application/octet-stream");
					MimeBodyPart mimeBodyPart = new MimeBodyPart();
					mimeBodyPart.setDataHandler(new DataHandler(source));
					mimeBodyPart.setFileName(attachment.getLabel());
					content.addBodyPart(mimeBodyPart);
				}
			}

			msg.setContent(content);
		} else {
			msg.setText(mess);
		}
		Transport.send(msg);
	}
}